<?
header('Content-Type: text/html; charset=UTF-8');
require 'crawl.php';
require '../libs/function.php';
require 'database.php';
$db = new DB();

$cat = isset($_GET['c']) ? strval($_GET['c']) : NULL;
$cat = trim($cat);

$url = 'http://www.gamepilot.com/games/' . $cat;

crawl($url);

function crawl($url) {
	global $db, $cat;
	$array = array();
	$num = 0;

	$html = file_get_html($url);
// 	echo $html;

	// similar categories
	$similar = $html->find('ul#js-similar-categories', 0)->innertext;
	$similar .= $html->find('ul#js-more-categories', 0)->innertext;
	$similar = str_get_html($similar);

	foreach ($similar->find('a') as $element){
		$plaintext = trim($element->plaintext);
		$plaintext = str_replace("'", '', $plaintext);
		$link = trim($element->href);
		$link = str_replace('http://www.gamepilot.com/games/', '', $link);

		$array['name'][] = $plaintext;
		$array['url'][] = $link;
	}

	foreach ($similar->find('img') as $element){
		$img = trim($element->src);
		$array['image'][] = $img;
	}

// 	echo '<pre>';
// 	print_r($array);
// 	echo '</pre>';
// 	exit();

	if (!empty($array)) {
		$cat = remove_unicode($cat, true);
		$total = count($array['url']);

		for ($i = 0; $i < $total; $i++) {
			// check url exists
			$Qry = 'SELECT url
					FROM cat
					WHERE url = "' . $array['url'][$i] . '"';

			if ($db->numRows($Qry) == 0) {
				$data = array(
						'parrent'=>$cat,
						'name'=>$array['name'][$i],
						'url'=>$array['url'][$i],
						'icon'=>$array['image'][$i]
				);

				$newID = $db->insert('cat', $data);
			}
		}

		echo $cat . ' ==> ' . $i . ' Sub';
	}
}